<?php

use Core\ResourceController;
use Models\Cart;

class CartController extends ResourceController
{
	public function add($id)
	{
		$item_id = $this->input->post('item_id');
		$qty = intval($this->input->post('qty'));
		$cart = new Cart;
		$cart_has = $cart->where('user_id',$this->session->authUser['id'])->where('item_id',$item_id)->get_one();
		if($cart_has){
			$cart->update($cart_has['id'],array('qty'=>$qty));
			return $this->validateError('已经加入过购物车了...');
		}
		$data['user_id'] = $this->session->authUser['id'];
		$data['product_id'] = $id;
		$data['item_id'] = $item_id;
		$data['qty'] = $qty;
		$data['create_time'] = date('Y-m-d H:i:s');
		$cart->add($data);
		$this->success();
	}

	/**
	 * 列表页
	 */
	public function index(){
			$cart = new Cart;
			$carts = $cart->select('carts.*,p.title as p_title,p.thumbnail,i.title as i_title,i.id as item_id,i.stock,i.weight,i.price')
			  ->join('products p','p.id = carts.product_id','left')
			  ->join('items i','i.id = carts.item_id')
			  ->where('carts.user_id',$this->session->authUser['id'])
			  ->where('i.is_delete',0)
			  ->where('p.is_delete',0)
			  ->where('p.status',1)
			  ->get();
		
		return $this->response($carts);
	}

	/**
	 * 删除购物车中商品
	 */
	public function delete(){
		$id = $this->input->post('id');
		$cart = new Cart;
		$ids = explode(',', $id);
		if(count($ids) == 1){
			$cart = $cart->find($id);
			if(!$cart){
				return $this->error('未找到此商品~~');
			}
			if($cart['user_id'] != $this->session->authUser['id']){
				return $this->error('请勿非法操作~~');
				exit;
			}
		}else{
			$carts = $cart->where_in('id',$ids)->where('user_id',$this->session->authUser['id'])->counts();
			if($carts != count($ids)){
				return $this->error('请勿非法操作~~');
				exit;
			}
		}
		
		$cart->delete($ids);
		return $this->success();
	}

	public function removeAll()
	{
		$ids = $this->input->post('ids');

		if ($ids) {
			Cart::where_in('id', $ids)
				->where('user_id', $this->session->authUser['id'])
				->deleteAll();
		}

		return $this->success();
	}

	/**
	 * 修改购物车数量
	 */
	public function change_qty($id)
	{
		$number = $this->input->post('qty');

		$cart = Cart::where(['user_id' => $this->session->authUser['id'], 'id' => $id])
			->get_one();
		if (!$cart) {
			return $this->notFoundResponse();
		}

		$cart['qty'] = $number;
		$cart->update();

		return $this->success();
	}
}